package xml;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class Dom4jTest {
	public static void main(String[] args) throws DocumentException, IOException {
		parseXml();
//		createPrintXML();
	}

	private static void createPrintXML() throws IOException {
		Document doc = DocumentHelper.createDocument();
		Element book = doc.addElement("book");
		book.addAttribute("isbn", "1234").addElement("title").addText("java");
		Element authors=
		book.addElement("authors");
		authors.addElement("author").addText("zs");
		authors.addElement("authors").addText("ls");
		
		OutputFormat f = OutputFormat.createPrettyPrint();
		XMLWriter writer = new XMLWriter(System.out,f);
		writer.write(doc);
	}

	private static void parseXml() throws DocumentException {
		SAXReader reader = new SAXReader();
		Document doc = reader.read(new File(
				"/home/tarena/0code/xml/sd1010_xml_day01_all.zip_FILES/test.html"));
//				"/home/tarena/0hean/hean/src/xml/email.xml"));
		Element root = doc.getRootElement();
		// 遍历
		// print(root);
		// 查找
		List<Element> nodes = doc.selectNodes("/email/to/to-email");
//		for (Element e : nodes) {
//			System.out.println(e.getText());
//		}
		List<Attribute> ns = doc.selectNodes("//a/@href");
		for (Attribute a : ns) {
//			System.out.println(a.getText());
			System.out.println(a.getValue());
		}
	}

	private static void print(Element e) {
		System.out.println("<" + e.getName() + ">");
		for (Iterator iter = e.attributeIterator(); iter.hasNext();) {
			Attribute element = (Attribute) iter.next();
			System.out.println(" " + element.getName() + "=\""
					+ element.getValue() + "\"");
		}
		if (e.isTextOnly()) {
			System.out.println(e.getText());
		} else {
			for (Iterator it = e.elementIterator(); it.hasNext();) {
				Element element = (Element) it.next();
				print(element);
			}
		}
		System.out.println("</" + e.getName() + ">");
	}
}
